#pragma semicolon 1
#pragma newdecls required

#include <sourcemod>
#include <left4dhooks>

#define	PLUGIN_VERSION	"1.0"

ArrayList g_hSavedPositions[MAXPLAYERS + 1];
bool g_bMissionFailed;

public Plugin myinfo = 
{
	name		= "l4d2_survivor_position_saver",
	author		= "豆瓣酱な",
	description	= "玩家团灭自动恢复原来的位置",
	version		= PLUGIN_VERSION,
	url		= "https://gitee.com/sweet-and-sour-bombs/adfvsdsd"
};

public void OnPluginStart()
{
	HookEvent("mission_lost", Event_MissionLost); //玩家团灭事件
	HookEvent("player_incapacitated", Event_PlayerIncapped); // 玩家倒地事件
    HookEvent("player_death", Event_PlayerIncapped, EventHookMode_Pre); // 在玩家死亡前触发	
    
	for (int i = 1; i <= MaxClients; i++)
	{
		g_hSavedPositions[i] = new ArrayList(3);
	}
}

public void OnClientDisconnect(int client)
{
	g_hSavedPositions[client].Clear();
}

public void Event_PlayerIncapped(Event event, const char[] name, bool dontBroadcast)
{
	int client = GetClientOfUserId(event.GetInt("userid"));
	if (IsValidClient(client) && GetClientTeam(client) == 2)
	{
		float pos[3];
		GetClientAbsOrigin(client, pos);
		g_hSavedPositions[client].Clear();
		g_hSavedPositions[client].PushArray(pos);
        
		//PrintToChat(client, "\x04[提示]\x01 你的倒地位置已记录");
	}
}

public void Event_MissionLost(Event event, const char[] name, bool dontBroadcast)
{
	if (g_bMissionFailed) return;
	g_bMissionFailed = true;
    
	PrintToChatAll("\x04[提示]\x01 任务失败！10秒后将传送回倒地位置...");
	CreateTimer(10.0, Timer_TeleportPlayers);
}

public Action Timer_TeleportPlayers(Handle timer)
{
	int teleportedCount = 0;
    
	for (int client = 1; client <= MaxClients; client++)
	{
		if (IsClientInGame(client) && GetClientTeam(client) == 2 && g_hSavedPositions[client].Length > 0)
		{
			float pos[3];
			g_hSavedPositions[client].GetArray(0, pos);
			TeleportEntity(client, pos, NULL_VECTOR, NULL_VECTOR);
			teleportedCount++;
            
			PrintToChat(client, "\x04[提示]\x01 你已被传送回倒地位置");
		}
	}
    
	//PrintToChatAll("\x04[提示]\x01 已传送 %d 名玩家回原位", teleportedCount);
	g_bMissionFailed = false;
	return Plugin_Continue;
}

bool IsValidClient(int client)
{
	return (client > 0 && client <= MaxClients && IsClientInGame(client));
}